class WebSocketService {
  constructor() {
    this.socket = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000;
    this.listeners = {};
    this.connected = false;
  }

  connect() {
    if (this.socket && this.connected) return;
    
    const token = localStorage.getItem('token');
    if (!token) return;
    
    // 根据实际环境配置WebSocket服务器地址
    const wsUrl = process.env.NODE_ENV === 'production' 
      ? `wss://${window.location.host}/ws` 
      : 'ws://localhost:3000/ws';
    
    this.socket = new WebSocket(`${wsUrl}?token=${token}`);
    
    this.socket.onopen = () => {
      console.log('WebSocket连接已建立');
      this.connected = true;
      this.reconnectAttempts = 0;
      this.triggerEvent('connect', {});
    };
    
    this.socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        this.triggerEvent('message', data);
      } catch (error) {
        console.error('解析WebSocket消息失败:', error);
      }
    };
    
    this.socket.onclose = () => {
      console.log('WebSocket连接已关闭');
      this.connected = false;
      this.reconnect();
    };
    
    this.socket.onerror = (error) => {
      console.error('WebSocket错误:', error);
      this.connected = false;
    };
  }
  
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数，停止重连');
      return;
    }
    
    this.reconnectAttempts++;
    console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
    
    setTimeout(() => {
      this.connect();
    }, this.reconnectInterval);
  }
  
  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
      this.connected = false;
    }
  }
  
  send(message) {
    if (!this.socket || !this.connected) {
      console.error('WebSocket未连接，无法发送消息');
      return false;
    }
    
    try {
      this.socket.send(JSON.stringify(message));
      return true;
    } catch (error) {
      console.error('发送WebSocket消息失败:', error);
      return false;
    }
  }
  
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  }
  
  off(event, callback) {
    if (!this.listeners[event]) return;
    
    if (callback) {
      this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
    } else {
      delete this.listeners[event];
    }
  }
  
  triggerEvent(event, data) {
    if (!this.listeners[event]) return;
    
    this.listeners[event].forEach(callback => {
      callback(data);
    });
  }
}

// 创建单例
const websocketService = new WebSocketService();
export default websocketService;